import { useBoolean, useDynamicList, useRequest } from 'ahooks';
import { Button, Empty, message, Row, Spin } from 'antd';
import React from 'react';
import request from '@/utils/request';
import Judgement from './Judgement';
import Space from '@/components/Space';

const DEFAULT_ITEM = {
  judgementObjectType: 'PREVIOUS_TASK_OUTPUT',
  judgementCondition: { type: 'BinaryExpression', op: 'eq', rhs: { isString: true } },
};

function ExclusiveGatewayEditor({
  gatewayId,
  versionId,
  readOnly,
  onCancel,
  onSaveAndValidVersion,
}) {
  const { list, push, remove, getKey, replace, resetList } = useDynamicList([]);
  const [onSubmitting, { setTrue: waitSubmitting, setFalse: finishSubmit }] = useBoolean(false);

  const { loading: onFetching } = useRequest(
    () => request.get(`/exclusiveGateway/queryVersionData?versionId=${versionId}`),
    {
      onSuccess({ judgements }) {
        resetList(
          judgements.map(({ judgementObjectType, judgementCondition, targetBranch }) => ({
            judgementObjectType,
            judgementCondition: JSON.parse(judgementCondition),
            targetBranch,
          }))
        );
      },
      refreshDeps: [versionId],
    }
  );

  const handleSave = () => {
    waitSubmitting();
    request
      .post('/exclusiveGateway/saveVersionData', {
        data: {
          versionId,
          judgements: list.map(({ judgementObjectType, judgementCondition, targetBranch }) => ({
            judgementObjectType,
            judgementCondition: JSON.stringify(judgementCondition),
            targetBranch,
          })),
        },
      })
      .then(() => {
        message.success('保存成功');
        onCancel();
      })
      .finally(() => {
        finishSubmit();
      });
  };

  const handleSaveAndValidVersion = () => {
    waitSubmitting();
    request
      .post('/exclusiveGateway/saveAndValidVersion', {
        data: {
          gatewayId,
          versionId,
          judgements: list.map(({ judgementObjectType, judgementCondition, targetBranch }) => ({
            judgementObjectType,
            judgementCondition: JSON.stringify(judgementCondition),
            targetBranch,
          })),
        },
      })
      .then(() => {
        message.success('保存并生效成功');
        onCancel();
        onSaveAndValidVersion && onSaveAndValidVersion();
      })
      .finally(() => {
        finishSubmit();
      });
  };

  function renderFooter() {
    if (readOnly) {
      return null;
    }
    return (
      <div className="modal-footer">
        <div className="pull-left">
          <Button icon="plus" type="link" style={{ padding: 0 }} onClick={() => push(DEFAULT_ITEM)}>
            添加判断
          </Button>
        </div>
        <Space className="pull-right">
          <Button style={{ marginRight: 8 }} onClick={onCancel}>
            取消
          </Button>
          <Button type="primary" onClick={handleSave} disabled={onFetching} loading={onSubmitting}>
            保存
          </Button>
          <Button
            type="primary"
            onClick={handleSaveAndValidVersion}
            disabled={onFetching}
            loading={onSubmitting}
          >
            保存并生效
          </Button>
        </Space>
      </div>
    );
  }

  return (
    <>
      <Spin spinning={onFetching || onSubmitting}>
        {list.length === 0 ? (
          <Empty />
        ) : (
          list.map((item, index) => (
            <Row key={getKey(index)} className="margin-bottom">
              <Judgement
                value={item}
                counter={index + 1}
                onRemove={() => remove(index)}
                onChange={value => replace(index, value)}
              />
            </Row>
          ))
        )}
      </Spin>
      {renderFooter()}
    </>
  );
}

export default ExclusiveGatewayEditor;
